package com.smartcampusbackend.controller;

import com.smartcampusbackend.model.ClassCircle;
import com.smartcampusbackend.model.ClassCircleMember;
import com.smartcampusbackend.model.User;
import com.smartcampusbackend.service.ClassCircleService;
import com.smartcampusbackend.service.TokenService;
import com.smartcampusbackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/class-circle")
@CrossOrigin(origins = "*")
public class ClassCircleController {

    @Autowired
    private ClassCircleService classCircleService;
    
    @Autowired
    private TokenService tokenService;
    
    @Autowired
    private UserService userService;

    // 获取当前登录用户信息
    private Integer getCurrentUserId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String username = tokenService.getUsernameByToken(token);
            if (username != null) {
                User user = userService.getByUsername(username);
                return user != null ? user.getId() : null;
            }
        }
        return null;
    }

    // 创建班级圈（仅教师）
    @PostMapping("/create")
    public ResponseEntity<?> createClassCircle(@RequestBody ClassCircle classCircle, HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            ClassCircle created = classCircleService.createClassCircle(classCircle, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "班级圈创建成功");
            response.put("data", created);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 删除班级圈（仅创建者）
    @DeleteMapping("/{classCircleId}")
    public ResponseEntity<?> deleteClassCircle(@PathVariable Integer classCircleId, HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            boolean result = classCircleService.deleteClassCircle(classCircleId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "班级圈删除成功");
            response.put("data", null);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 搜索班级圈
    @GetMapping("/search")
    public ResponseEntity<?> searchClassCircle(@RequestParam String classId) {
        try {
            ClassCircle classCircle = classCircleService.searchByClassId(classId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "搜索成功");
            response.put("data", classCircle);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 加入班级圈
    @PostMapping("/{classCircleId}/join")
    public ResponseEntity<?> joinClassCircle(@PathVariable Integer classCircleId, HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            boolean result = classCircleService.joinClassCircle(classCircleId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "成功加入班级圈");
            response.put("data", null);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 退出班级圈
    @PostMapping("/{classCircleId}/leave")
    public ResponseEntity<?> leaveClassCircle(@PathVariable Integer classCircleId, HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            boolean result = classCircleService.leaveClassCircle(classCircleId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "成功退出班级圈");
            response.put("data", null);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取用户创建的班级圈
    @GetMapping("/my-created")
    public ResponseEntity<?> getMyCreatedCircles(HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            List<ClassCircle> circles = classCircleService.getUserCreatedCircles(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", circles);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取用户加入的班级圈
    @GetMapping("/my-joined")
    public ResponseEntity<?> getMyJoinedCircles(HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            List<ClassCircle> circles = classCircleService.getUserJoinedCircles(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", circles);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取班级圈成员
    @GetMapping("/{classCircleId}/members")
    public ResponseEntity<?> getClassCircleMembers(@PathVariable Integer classCircleId) {
        try {
            List<ClassCircleMember> members = classCircleService.getClassCircleMembers(classCircleId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", members);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 检查用户是否已加入班级圈
    @GetMapping("/{classCircleId}/is-joined")
    public ResponseEntity<?> isUserJoined(@PathVariable Integer classCircleId, HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            boolean isJoined = classCircleService.isUserJoined(classCircleId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "检查成功");
            response.put("data", isJoined);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 教师删除班级圈成员
    @DeleteMapping("/{classCircleId}/members/{memberId}")
    public ResponseEntity<?> removeClassCircleMember(@PathVariable Integer classCircleId, 
                                                   @PathVariable Integer memberId, 
                                                   HttpServletRequest request) {
        try {
            Integer operatorUserId = getCurrentUserId(request);
            if (operatorUserId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            String token = request.getHeader("Authorization");
            String username = null;
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                username = tokenService.getUsernameByToken(token);
            }
            User user = userService.getByUsername(username);
            boolean isAdmin = user != null && "ADMIN".equals(user.getRole());
            boolean result = classCircleService.removeClassCircleMember(classCircleId, memberId, operatorUserId, isAdmin);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "成员删除成功");
            response.put("data", null);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取所有班级圈（仅管理员）
    @GetMapping("/all")
    public ResponseEntity<?> getAllClassCircles(HttpServletRequest request) {
        Integer userId = getCurrentUserId(request);
        if (userId == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 401);
            response.put("message", "用户未登录");
            response.put("data", null);
            return ResponseEntity.status(401).body(response);
        }
        User user = userService.getById(userId);
        if (user == null || !"ADMIN".equals(user.getRole())) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 403);
            response.put("message", "无权限");
            response.put("data", null);
            return ResponseEntity.status(403).body(response);
        }
        List<ClassCircle> circles = classCircleService.getAllClassCircles();
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取成功");
        response.put("data", circles);
        return ResponseEntity.ok(response);
    }
} 